package com.fc.v2.common.file;

import com.fc.v2.common.conf.FileConfig;
import com.fc.v2.common.conf.V2Config;
import com.fc.v2.common.exception.file.FileNameLengthLimitExceededException;
import com.fc.v2.util.StringUtils;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 文件上传工具类
 * @author fuce 
 * @date: 2018年9月22日 下午10:33:23
 */
@Component
public class FileUploadUtils {

    private static Logger log =  LoggerFactory.getLogger(FileUploadUtils.class);

    @Autowired
    private V2Config v2Config;

    private FileUploadUtils(){}
    
    /**
     * spring.servlet.multipart.maxFileSize
     */
    public static  long DEFAULT_MAX_SIZE=Long.valueOf(FileConfig.getMaxFileSize())*1024*1024;
    /**
     * 默认上传的地址
     */
    private static String relativePath;

    private static String absolutePath;

    private static String customPathEnable;
    
    /**
     * 默认的文件名最大长度
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;
    /**
     * 默认文件类型jpg
     */
    public static final String IMAGE_JPG_EXTENSION = ".jpg";
    public static final List<String> IMAGE_EXTENSION_LIST = Arrays.asList(".jpg",".png",".jpeg",".bmp");
    public static final String MOVIE_EXTENSION = ".mp4";

    private static int counter = 0;


    private static Integer imgWidth;
    private static Integer imgHeight;


	@PostConstruct
	public void init(){
        relativePath = v2Config.getRelativePath();
        absolutePath = v2Config.getAbsolutePath();
        customPathEnable = v2Config.getCustomPathEnable();

        imgWidth = v2Config.getImgWidth();
        imgHeight = v2Config.getImgHeight();

    }



	/**
	 * 静态文件上传后存放的目录
	 */
	public static String getStaticPath() {
		String url=ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/"+relativePath;
		return url;
	}

    public static String getCustomPath() {
        return absolutePath;
    }


	/**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static final String upload(MultipartFile file,Boolean imgCut) throws IOException
    {
        try
        {
        	if("Y".equals(customPathEnable)) {//获取根目录
        		
        		 return upload(getCustomPath(), file,imgCut);
        	}else {//自定义目录
        		 return upload(getStaticPath(), file,imgCut);
        	}
        }
        catch (Exception e)
        {
            throw new IOException(e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @param needDatePathAndRandomName 是否需要日期目录和随机文件名前缀
     * @param extension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException 比如读写文件出错时
     */
    public static final String upload(String baseDir, MultipartFile file,Boolean imgCut)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException
    {
    	String fileName=file.getOriginalFilename();
    	// 获得文件后缀名称
    	String suffixName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
    	if(StringUtils.isEmpty(suffixName)) {
    		//如果没有后缀默认后缀
    		suffixName=FileUploadUtils.IMAGE_JPG_EXTENSION;
    	}
    	
        int fileNamelength = fileName.length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(fileName, fileNamelength,
                    FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file);

        String new_fileName = encodingFilename(fileName, suffixName);

        File desc = getAbsoluteFile( baseDir, new_fileName);

        file.transferTo(desc);

//        //如果是图片，进行处理
        if(IMAGE_EXTENSION_LIST.contains(suffixName)){
            log.debug("正在压缩图片");

            Thumbnails.Builder<File> builder = Thumbnails.of(desc);

            //读取图片长宽，再压缩为defaultImageSize*defaultImageSize
            BufferedImage sourceImg  = ImageIO.read(desc);
            int width = sourceImg.getWidth();
            int height = sourceImg.getHeight();

            if(imgCut){
                //            图片比规定尺寸小的情况
                if(height < imgHeight || width < imgWidth){
                    int minLength = getMinLength(width, height);
                    int newHeight=height;
                    int newWidth=width;
                    if(height < width){
                        newWidth = height/2;
                    } else {
                        newHeight = width/2;
                    }
                    builder = builder.sourceRegion(Positions.TOP_LEFT, newWidth, newHeight).size(imgWidth, imgHeight).keepAspectRatio(false);

                }else{
                    builder = builder.sourceRegion(Positions.TOP_LEFT, imgWidth, imgHeight).size(imgWidth, imgHeight).keepAspectRatio(false);
                }

            }else{
//                只压缩
                builder = builder.size(imgWidth, imgHeight);
            }

            builder.toFile(desc);
            log.debug("压缩成功");
        }else{
            log.debug("不是图片，不压缩");
        }

        return new_fileName;
    }

    private static final int getMinLength(int width, int height){
        return width>height?height:width;
    }
    private static final int getMaxLength(int width, int height){
        return width<height?height:width;
    }

    private static final File getAbsoluteFile(String baseDir,String filename) throws IOException
    {
        File desc = new File(baseDir,filename);

        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists())
        {
            desc.createNewFile();
        }
        return desc;
    }

    /**
     * 编码文件名
     */
    private static final String encodingFilename(String filename, String extension)
    {
        filename = filename.replace("_", " ");
        filename = new Md5Hash(filename + System.nanoTime() + counter++).toHex().toString() + extension;
        return filename;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     */
    public static final void assertAllowed(MultipartFile file) throws FileSizeLimitExceededException
    {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
        {
            throw new FileSizeLimitExceededException("超过默认大小", size, DEFAULT_MAX_SIZE);
        }
    }

}
